import React, { ReactNode, useCallback, useContext, useEffect, useState } from "react";
import { HistoryLinkedList, HistoryNode } from "./modal/HistoryModal";

interface MainContentType {
    menuContent: ReactNode
    history: HistoryLinkedList<ReactNode>;
    setFirstHistory: (newContent:ReactNode) => void;
    getCurrent: () => ReactNode;
    to: (content:ReactNode) => void;
    goBack: () => void;
    canGoBack: boolean;
    setMenuContent: (menuCOntent:ReactNode) => void;
}
const defaultNode:HistoryNode<ReactNode> = {
    data: <></>,
    next: null,
    prev: null
}
const MainContentContext = React.createContext<MainContentType>({} as MainContentType);

export const MainContentProvider = ({children}: {children: ReactNode}) => {
    const [history] = useState<HistoryLinkedList<ReactNode>>(() => new HistoryLinkedList<ReactNode>(<></>));
    const [menuContent, setMenuContent] = useState<ReactNode>(<></>);

    const getCurrent = useCallback(() => {
        const result = history.getCurrent()?.data || defaultNode.data;
        setMenuContent(result);
        return result;
    },[history]);

    const to = useCallback((newContent:ReactNode) => {
        history.add(newContent);
        setMenuContent(newContent);
    },[history]);

    const setFirstHistory = useCallback((newContent: ReactNode) => {
        history.toHead();
        history.add(newContent);
        setMenuContent(newContent);
    },[history]);

    const goBack = useCallback(() => {
        history.backward();
        history.clearNext();
        setMenuContent(history.getCurrent()?.data || null);
    },[history]);

    return (
        <MainContentContext.Provider value={{ menuContent,history,setFirstHistory,getCurrent,to,goBack,canGoBack: history.canBackward(),setMenuContent }}>
            {children}
        </MainContentContext.Provider>
    );
}

export const useMainContentContext = () => useContext(MainContentContext);